<template>
    <el-row class="file-div">
        <div v-if="Object.keys(stageList).length === 0" class="empty-message stageStyle">
            请先选择您要查看的班级
        </div>
        <el-menu v-else default-active="2" class="file-list" :default-openeds="[stageList.length-1]">
            <el-sub-menu v-for="(item, index) in stageList" :key="index" :index="index"
                class="item-with-icon">
                <template #title>
                    <el-icon><FolderOpened color="#58a0c3" size="20px"/></el-icon>
                    <span class ="stageStyle">第{{ item.stage }}阶段</span>
                    <div class="icon-group">
                        <el-icon class="icon" @click.stop="handleAddFile(item)">
                            <DocumentAdd />
                        </el-icon>
                    </div>
                </template>

                <el-menu-item v-for="(node, index) in item.nodes" :key="node" :index="node.title + '-' + index"
                    @click="handleNodeId(node)">
                    <div v-if="node.isEditing" class="edit-node">
                        <el-input v-model="node.editTitle" placeholder="请输入标题" @keyup.enter="saveNodeTitle(item, index)"
                            @blur="saveNodeTitle(item, index)" :placeholderSign="getDefaultFileName(item)" size="small"
                            ref="inputRefs" class="input-title" />
                    </div>
                    <div v-if="node.showDuplicateError" class="error-message">
                        文件名已存在，请使用其他名称
                    </div>
                    <div v-else-if="!node.isEditing" class="nodeTitle">
                        <span class="node-title">
                            <el-icon ><Notebook color="#56b0c3"/></el-icon>
                            <span class ="stageStyle">{{ node.title }}</span>
                        </span>
                        <span class="icon-child-group">
                            <el-icon class="icons">
                                <DocumentRemove @click.stop="confirmDeleteNode(node,item)"/>
                            </el-icon>
                        </span>
                    </div>
                </el-menu-item>
            </el-sub-menu>
        </el-menu>
    </el-row>
</template>

<script lang="ts" setup>
import { onMounted, ref, nextTick, watch } from 'vue'
import { storeInfo } from '@/stores/storeinfo';
import { nodeinfo } from '@/stores/nodeinfo';
import { useEditorStore } from '@/stores/editStore'
import { DocumentAdd, DocumentRemove } from '@element-plus/icons-vue'
import { uuid } from '@/utils/uuid';
import { currentNodeInfo } from '@/stores/currentNodeStore';
import { ElMessageBox } from 'element-plus';
import { useCommentPluginStore } from '@/stores/commentPluginStore';
import { useCommentStore } from '@/stores/commentStore'
import { useUserStore } from '@/stores/userStore'
const editorStore = useEditorStore();
const storeinfo = storeInfo();
const currentNodeStore = currentNodeInfo()
// 获取共享数据
let classToFile = storeinfo.sharedData;
//这里后期要换成登录的用户信息
const userId = useUserStore().user.id;
const username = useUserStore().user.name;
const nodeinfoStore = nodeinfo();
let stageList = ref({})
const inputRefs = ref([]);

watch (
    () => storeinfo.sharedData,
    (newVal, oldVal) => {
            console.log('targetValue 变化了', newVal, oldVal);
            classToFile = newVal
        if (!newVal) {
            console.error("没有获取到共享数据，请确保在父组件中设置了共享数据。");
        } else {
            //获取阶段数组
            const stages = newVal.stages;
            const nodeQueryInfo = ref({
                classId: newVal.id,
                userId: userId.value,
                stage: stages
            })
            console.log("-----------------",nodeQueryInfo.value);
            
            //使用Promise来确保数据获取完成
            nodeinfoStore.getNodeInfo(nodeQueryInfo.value).then((res) => {
                // stageList.value = res
                // 确保数据获取完成后再执行其他操作
                console.log("获取到的查询笔记的信息：", res);
                stageList.value = res
            }).catch((error) => {
                console.error("获取笔记信息失败：", error);
            });
            // stageList.value =nodeinfoStore.stageList
            // console.log("获取到的查询笔记的信息：", stageList.value);
            
        }
        // 这里写状态变化后要执行的逻辑，比如发请求、更新其他状态等
    },
    // 第一次进来就会有效果
    { immediate: true, deep: true }
);

const handleOpen = (key: string, keyPath: string[]) => {
    console.log(key, keyPath)
}
const handleClose = (key: string, keyPath: string[]) => {
    console.log(key, keyPath)
}

const handleNodeId =async (currentNode: any) => {
   // 1️⃣ 保存当前批注（若有更改）
  try {
    await useCommentStore().save()
    console.log('已自动保存当前批注')
  } catch (e) {
    console.warn('批注保存失败:', e)
  }
    storeinfo.setNowContent(currentNode.content)
    editorStore.getCurrentNode(currentNode.nodeId)
    await useCommentStore().load(currentNode.nodeId, userId)
    const commentPlugin = useCommentPluginStore().pluginInstance
    commentPlugin.loadComments?.(useCommentStore().commentList);
    console.log("渲染的批注", useCommentStore().commentList);

}

//新建文件

// 获取默认文件名（带序号）
const getDefaultFileName = (stageItem: any) => {
    let defaultName = '新建文件';
    let counter = 1;

    while (isFileNameDuplicate(stageItem, `${defaultName}${counter > 1 ? ` ${counter}` : ''}`)) {
        counter++;
    }

    return `${defaultName}${counter > 1 ? ` ${counter}` : ''}`;
}

// 检查文件名是否重复
const isFileNameDuplicate = (stageItem: any, fileName: string, excludeIndex?: number) => {
    if (!stageItem.nodes) return false;

    return stageItem.nodes.some((node: any, index: number) => {
        // 排除自身检查
        if (excludeIndex !== undefined && index === excludeIndex) return false;
        return node.title === fileName;
    });
}
let newNode = ref({})
const handleAddFile = (item: any) => {
    console.log("点击获取的信息：", item);
    // 添加新节点（处于编辑状态）

    newNode.value = {
        nodeId:uuid(),
        title: '', // 初始为空，用户必须输入
        isEditing: true,
        editTitle: '', // 初始为空
        stage: item.stage,
        classId: classToFile.id,
        userId: userId.value,
        showDuplicateError: false
    };

    if (!item.nodes) {
        item.nodes = [];
    }

    item.nodes.push(newNode.value);

    // 自动展开当前子菜单
    const subMenuIndex = item.stage.toString();
    const activeIndexes = document.querySelectorAll('.el-sub-menu.is-opened');
    activeIndexes.forEach(el => {
        if (el.getAttribute('index') !== subMenuIndex) {
            el.classList.remove('is-opened');
        }
    });

    // 确保当前子菜单展开
    nextTick(() => {
        const currentSubMenu = document.querySelector(`.el-sub-menu[index="${subMenuIndex}"]`);
        if (currentSubMenu && !currentSubMenu.classList.contains('is-opened')) {
            currentSubMenu.classList.add('is-opened');
        }

        // 聚焦到新添加的输入框
        if (inputRefs.value && inputRefs.value.length > 0) {
            const lastInput = inputRefs.value[inputRefs.value.length - 1];
            lastInput.focus();
        }
    });
}
let newNodeInfo = ref({})
// 保存节点标题（回车或失焦时触发） 也就是创建成功了
const saveNodeTitle =  (item: any, nodeIndex: number) => {
    const node = item.nodes[nodeIndex];
    const newTitle = node.editTitle.trim();

    if (!newTitle) {
        // 如果标题为空，则删除该节点
        item.nodes.splice(nodeIndex, 1);
        return;
    }

    // 检查文件名是否重复（排除自身）
    if (isFileNameDuplicate(item, newTitle, nodeIndex)) {
        node.showDuplicateError = true;
        // 保持编辑状态
        node.isEditing = true;
        // 重新聚焦输入框
        nextTick(() => {
            if (inputRefs.value && inputRefs.value[nodeIndex]) {
                inputRefs.value[nodeIndex].focus();
                inputRefs.value[nodeIndex].select();
            }
        });
        return;
    }

    node.showDuplicateError = false;
    node.title = newTitle;
    node.isEditing = false;


    newNodeInfo.value={
        nodeId: newNode.value.nodeId,
        title: newTitle,
        teacherId: userId,
        classId: classToFile.id,
        stage: item.stage,
        createdAuthor: username
    }
    console.log("新增笔记信息：", newNodeInfo.value);
    //调用接口存入数据库
    nodeinfoStore.insertnewNode(newNodeInfo.value);
    //存入pinia
    storeinfo.setNewNodeInfo(newNodeInfo.value);
}

// 确认删除文件
const confirmDeleteNode = (node:any,item:any) => {
    ElMessageBox.confirm(
        `确定要删除文件 "${node.title}" 吗？`,
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        await deleteNode(node,item);
        // 从UI中立即移除该节点
        for (const stage of Object.values(stageList.value)) {
            if (stage.nodes) {
                const index = stage.nodes.findIndex(n => n.nodeId === node.nodeId);
                if (index !== -1) {
                    stage.nodes.splice(index, 1);
                    break;
                }
            }
        }
    }).catch(() => {
        // 用户点击了取消
        console.log('取消删除');
    });
}

//删除文件
const deleteNode = async (node:any,item:any) => {
    console.log("删除时获取nodeId和stage", node.nodeId,"，",item.stage);
    const nodeId = node.nodeId;
    const stage = item.stage;
    const classId = classToFile.id
    await nodeinfoStore.deleteNode({nodeId,stage,classId});
}

</script>
<style scoped>
.input-title {
    display: flex;
    align-items: start;
}

.error-message {
    position: absolute;
    left: 0;
    bottom: 0px;
    /* 将错误信息定位在输入框下方 */
    color: #f56c6c;
    font-size: 10px;
    line-height: 1;
    padding-top: 2px;
    display: flex;
    padding-left: 20%;
}

/* 当有错误时，调整输入框边框颜色 */
.is-error :deep(.el-input__wrapper) {
    box-shadow: 0 0 0 1px #f56c6c inset;
}

/* 子菜单项的图标控制 */
.icon-child-group {
    opacity: 0;
    transition: opacity 0.2s ease;
    /* display: flex; */
    position: absolute;
    right: 20px;

}

/* 使用更精确的选择器确保生效 */
:deep(.el-menu-item):hover .icon-child-group,
.el-menu-item:hover .icon-child-group {
    opacity: 1;
}

/* 初始状态下隐藏图标 */
.item-with-icon .icon-group {
    opacity: 0;
    transition: opacity 0.3s ease;
}

/* 鼠标悬停时显示图标 */
.item-with-icon:hover .icon-group {
    opacity: 1;
}

:deep(.el-sub-menu .el-sub-menu__title) {
    background-color: #bfd6ee;
}

/* 修改菜单项高度 */
.file-list :deep(.el-menu-item),
.file-list :deep(.el-sub-menu__title) {
    height: 45px;
    /* 设置为你想要的高度 */
    line-height: 45px;
    /* 保持与高度一致以确保垂直居中 */
}

.icon-group {
    display: flex;
    gap: 0px;
    position: absolute;
    right: 30px;
}

.item-with-icon {
    position: relative;
}

.file-div {
    overflow: auto;
    text-align: center;
    border-radius: 10px;
}

.file-list {
    width: 100%;
}

/* 菜单项文本自动换行 */
.el-menu-item span,
.el-sub-menu__title span {
    white-space: normal;
    word-break: break-word;
}
/* 字体 */
.stageStyle{
    font-size: 19px;
    padding-left: 20px;
}
</style>
